<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- CSRF元数据 -->
    <meta name="_csrf" th:content="${_csrf.token}"/>
    <meta name="_csrf_header" th:content="${_csrf.headerName}"/>
    <meta name="_csrf_parameter" th:content="${_csrf.parameterName}"/>
    <title>产品管理 - 农产品物流园管理系统</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap4.min.css">
    <link rel="stylesheet" th:href="@{/css/style.css}">
    <style>
        .content-header {
            margin-bottom: 20px;
        }
        .product-container {
            padding: 20px;
        }
        .action-btn {
            margin-right: 5px;
        }
        .dataTables_wrapper {
            padding: 0;
        }
        .form-group.required .control-label:after {
            content: "*";
            color: red;
        }
        .modal-footer {
            justify-content: space-between;
        }
        .product-image {
            max-width: 80px;
            max-height: 80px;
            border-radius: 4px;
        }
        .preview-image {
            max-width: 100px;
            max-height: 100px;
            margin-top: 10px;
            border-radius: 4px;
            display: none;
        }
    </style>
</head>
<body>
    <div class="product-container">
        <!-- 内容头部 -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0"><i class="fas fa-box mr-2"></i>产品管理</h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="#" onclick="parent.loadContent('dashboard')">首页</a></li>
                            <li class="breadcrumb-item active">产品管理</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- 主要内容 -->
        <div class="container-fluid">
            <!-- 卡片 -->
            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-8">
                            <h3 class="card-title">产品信息列表</h3>
                        </div>
                        <div class="col-md-4 text-right">
                            <button type="button" class="btn btn-primary" onclick="addProduct()">
                                <i class="fas fa-plus"></i> 添加产品
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <!-- 搜索表单 -->
                    <div class="row mb-3">
                        <div class="col-md-12">
                            <form id="searchForm" class="form-inline">
                                <div class="form-group mb-2 mr-3">
                                    <label for="searchName" class="mr-2">产品名称:</label>
                                    <input type="text" class="form-control" id="searchName" placeholder="输入产品名称">
                                </div>
                                <div class="form-group mb-2 mr-3">
                                    <label for="searchCategory" class="mr-2">产品类别:</label>
                                    <select class="form-control" id="searchCategory">
                                        <option value="">全部</option>
                                        <option value="1">谷物类</option>
                                        <option value="2">蔬菜类</option>
                                        <option value="3">水果类</option>
                                        <option value="4">肉类</option>
                                        <option value="5">水产类</option>
                                    </select>
                                </div>
                                <div class="form-group mb-2 mr-3">
                                    <label for="searchStatus" class="mr-2">状态:</label>
                                    <select class="form-control" id="searchStatus">
                                        <option value="">全部</option>
                                        <option value="0">正常</option>
                                        <option value="1">停用</option>
                                    </select>
                                </div>
                                <button type="button" class="btn btn-primary mb-2 mr-2" onclick="searchProducts()">
                                    <i class="fas fa-search"></i> 搜索
                                </button>
                                <button type="button" class="btn btn-secondary mb-2" onclick="resetSearch()">
                                    <i class="fas fa-sync-alt"></i> 重置
                                </button>
                            </form>
                        </div>
                    </div>

                    <!-- 数据表格 -->
                    <div class="table-responsive">
                        <table id="simpleProductTable" class="table table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>图片</th>
                                    <th>产品名称</th>
                                    <th>产品编号</th>
                                    <th>分类</th>
                                    <th>单位</th>
                                    <th>规格</th>
                                    <th>单价(元)</th>
                                    <th>保质期(天)</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- 示例数据 -->
                                <tr>
                                    <td>1</td>
                                    <td><img src="/images/no-image.png" class="product-image"></td>
                                    <td>有机大米</td>
                                    <td>P001</td>
                                    <td>谷物类</td>
                                    <td>kg</td>
                                    <td>5kg/袋</td>
                                    <td>25.00</td>
                                    <td>365</td>
                                    <td><span class="badge badge-success">正常</span></td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <button type="button" class="btn btn-sm btn-info action-btn" onclick="viewProduct(1)">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-primary action-btn" onclick="editProduct(1)">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-danger action-btn" onclick="showDeleteModal(1)">
                                                <i class="fas fa-trash-alt"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td>2</td>
                                    <td><img src="/images/no-image.png" class="product-image"></td>
                                    <td>新鲜胡萝卜</td>
                                    <td>P002</td>
                                    <td>蔬菜类</td>
                                    <td>kg</td>
                                    <td>散装</td>
                                    <td>3.50</td>
                                    <td>7</td>
                                    <td><span class="badge badge-success">正常</span></td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <button type="button" class="btn btn-sm btn-info action-btn" onclick="viewProduct(2)">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-primary action-btn" onclick="editProduct(2)">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-danger action-btn" onclick="showDeleteModal(2)">
                                                <i class="fas fa-trash-alt"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td>3</td>
                                    <td><img src="/images/no-image.png" class="product-image"></td>
                                    <td>红富士苹果</td>
                                    <td>P003</td>
                                    <td>水果类</td>
                                    <td>kg</td>
                                    <td>精品装</td>
                                    <td>12.80</td>
                                    <td>15</td>
                                    <td><span class="badge badge-success">正常</span></td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <button type="button" class="btn btn-sm btn-info action-btn" onclick="viewProduct(3)">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-primary action-btn" onclick="editProduct(3)">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-danger action-btn" onclick="showDeleteModal(3)">
                                                <i class="fas fa-trash-alt"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑产品模态框 -->
    <div class="modal fade" id="productModal" tabindex="-1" role="dialog" aria-labelledby="productModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="productModalLabel">添加产品</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="productForm">
                        <input type="hidden" id="productId" name="productId">
                        <div class="form-row">
                            <div class="form-group required col-md-6">
                                <label for="productName" class="control-label">产品名称:</label>
                                <input type="text" class="form-control" id="productName" name="productName" required>
                            </div>
                            <div class="form-group required col-md-6">
                                <label for="productCode" class="control-label">产品编号:</label>
                                <input type="text" class="form-control" id="productCode" name="productCode" required>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group required col-md-6">
                                <label for="categoryId" class="control-label">产品分类:</label>
                                <select class="form-control" id="categoryId" name="categoryId" required>
                                    <option value="">请选择分类</option>
                                    <option value="1">谷物类</option>
                                    <option value="2">蔬菜类</option>
                                    <option value="3">水果类</option>
                                    <option value="4">肉类</option>
                                    <option value="5">水产类</option>
                                </select>
                            </div>
                            <div class="form-group col-md-6">
                                <label for="status">状态:</label>
                                <select class="form-control" id="status" name="status">
                                    <option value="0">正常</option>
                                    <option value="1">停用</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group required col-md-6">
                                <label for="unit" class="control-label">单位:</label>
                                <input type="text" class="form-control" id="unit" name="unit" required>
                            </div>
                            <div class="form-group col-md-6">
                                <label for="spec">规格:</label>
                                <input type="text" class="form-control" id="spec" name="spec">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <label for="weight">重量(kg):</label>
                                <input type="number" class="form-control" id="weight" name="weight" min="0" step="0.01">
                            </div>
                            <div class="form-group required col-md-6">
                                <label for="price" class="control-label">单价(元):</label>
                                <input type="number" class="form-control" id="price" name="price" min="0" step="0.01" required>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <label for="shelfLife">保质期(天):</label>
                                <input type="number" class="form-control" id="shelfLife" name="shelfLife" min="0">
                            </div>
                            <div class="form-group col-md-6">
                                <label for="storageCondition">存储条件:</label>
                                <input type="text" class="form-control" id="storageCondition" name="storageCondition">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="picUrl">产品图片:</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="picUrl" name="picUrl">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="button" onclick="$('#fileInput').click()">
                                        浏览
                                    </button>
                                </div>
                            </div>
                            <input type="file" id="fileInput" style="display: none;" accept="image/*" onchange="previewImage(this)">
                            <img id="imagePreview" class="preview-image">
                        </div>
                        <div class="form-group">
                            <label for="remark">备注:</label>
                            <textarea class="form-control" id="remark" name="remark" rows="2"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" id="deleteBtn" onclick="confirmDelete()" style="display:none;">
                        <i class="fas fa-trash-alt"></i> 删除
                    </button>
                    <div>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveProduct()">保存</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认删除模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>确定要删除这个产品吗？此操作不可恢复。</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" onclick="deleteProduct()">确认删除</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>
    <script>
        // 简单的产品管理变量
        var editingId = typeof editingId !== 'undefined' ? editingId : null;
        var token = typeof token !== 'undefined' ? token : $("meta[name='_csrf']").attr("content");
        var header = typeof header !== 'undefined' ? header : $("meta[name='_csrf_header']").attr("content");

        $(document).ready(function() {
            // 添加CSRF令牌到所有AJAX请求
            $.ajaxSetup({
                beforeSend: function(xhr) {
                    xhr.setRequestHeader(header, token);
                }
            });

            // 初始化简单的表格排序和搜索功能
            $('#searchForm').on('submit', function(e) {
                e.preventDefault();
                searchProducts();
            });
        });

        // 添加产品
        function addProduct() {
            editingId = null;
            $('#productModalLabel').text('添加产品');
            $('#productForm')[0].reset();
            $('#productId').val('');
            $('#imagePreview').hide();
            $('#deleteBtn').hide();
            $('#productModal').modal('show');
        }

        // 图片预览功能
        function previewImage(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                
                reader.onload = function(e) {
                    $('#imagePreview').attr('src', e.target.result).show();
                    // 这里应该上传图片到服务器，然后将返回的URL放入picUrl字段
                    // 简化起见，这里直接将base64数据放入picUrl
                    $('#picUrl').val(e.target.result);
                }
                
                reader.readAsDataURL(input.files[0]);
            }
        }

        // 查看产品详情
        function viewProduct(id) {
            // 获取产品数据 - 这里使用模拟数据
            var mockData = getMockProductData(id);
            if (mockData) {
                // 填充表单
                $('#productId').val(mockData.productId);
                $('#productName').val(mockData.productName);
                $('#productCode').val(mockData.productCode);
                $('#categoryId').val(mockData.categoryId);
                $('#status').val(mockData.status);
                $('#unit').val(mockData.unit);
                $('#spec').val(mockData.spec);
                $('#weight').val(mockData.weight);
                $('#price').val(mockData.price);
                $('#shelfLife').val(mockData.shelfLife);
                $('#storageCondition').val(mockData.storageCondition);
                $('#picUrl').val(mockData.picUrl);
                $('#remark').val(mockData.remark);
                
                // 显示图片预览
                if (mockData.picUrl) {
                    $('#imagePreview').attr('src', mockData.picUrl).show();
                } else {
                    $('#imagePreview').hide();
                }
                
                // 设置字段为只读
                $('#productForm input, #productForm select, #productForm textarea').prop('disabled', true);
                
                // 设置模态框标题和显示
                $('#productModalLabel').text('查看产品详情');
                $('#deleteBtn').hide();
                
                // 隐藏保存按钮，修改关闭按钮文本
                $('.modal-footer .btn-primary').hide();
                $('.modal-footer .btn-secondary').text('关闭');
                
                $('#productModal').modal('show');
            } else {
                alert('获取产品信息失败: 未找到该产品');
            }
        }

        // 编辑产品
        function editProduct(id) {
            editingId = id;
            
            // 重置表单状态
            $('#productForm')[0].reset();
            $('#productForm input, #productForm select, #productForm textarea').prop('disabled', false);
            $('.modal-footer .btn-primary').show().text('保存');
            $('.modal-footer .btn-secondary').text('取消');
            
            // 获取产品数据 - 这里使用模拟数据
            var mockData = getMockProductData(id);
            if (mockData) {
                // 填充表单
                $('#productId').val(mockData.productId);
                $('#productName').val(mockData.productName);
                $('#productCode').val(mockData.productCode);
                $('#categoryId').val(mockData.categoryId);
                $('#status').val(mockData.status);
                $('#unit').val(mockData.unit);
                $('#spec').val(mockData.spec);
                $('#weight').val(mockData.weight);
                $('#price').val(mockData.price);
                $('#shelfLife').val(mockData.shelfLife);
                $('#storageCondition').val(mockData.storageCondition);
                $('#picUrl').val(mockData.picUrl);
                $('#remark').val(mockData.remark);
                
                // 显示图片预览
                if (mockData.picUrl) {
                    $('#imagePreview').attr('src', mockData.picUrl).show();
                } else {
                    $('#imagePreview').hide();
                }
                
                // 设置模态框标题和显示
                $('#productModalLabel').text('编辑产品');
                $('#deleteBtn').show();
                $('#productModal').modal('show');
            } else {
                alert('获取产品信息失败: 未找到该产品');
            }
        }

        // 保存产品信息
        function saveProduct() {
            // 表单验证
            if (!$('#productForm')[0].checkValidity()) {
                $('#productForm')[0].reportValidity();
                return;
            }
            
            // 收集表单数据
            const formData = {
                productId: $('#productId').val(),
                productName: $('#productName').val(),
                productCode: $('#productCode').val(),
                categoryId: $('#categoryId').val(),
                status: $('#status').val(),
                unit: $('#unit').val(),
                spec: $('#spec').val(),
                weight: $('#weight').val(),
                price: $('#price').val(),
                shelfLife: $('#shelfLife').val(),
                storageCondition: $('#storageCondition').val(),
                picUrl: $('#picUrl').val(),
                remark: $('#remark').val()
            };
            
            // 确定是新增还是更新
            const isNew = !formData.productId;
            
            // 模拟保存成功
            $('#productModal').modal('hide');
            alert(isNew ? '添加产品成功！' : '更新产品成功！');
            
            // 在实际应用中，这里应该发送AJAX请求到后端保存数据
            // 然后重新加载表格数据
        }

        // 显示删除确认对话框
        function showDeleteModal(id) {
            editingId = id;
            $('#deleteModal').modal('show');
        }

        // 从编辑模态框中删除
        function confirmDelete() {
            if (editingId) {
                $('#productModal').modal('hide');
                setTimeout(() => {
                    $('#deleteModal').modal('show');
                }, 500);
            }
        }

        // 删除产品
        function deleteProduct() {
            if (editingId) {
                // 模拟删除成功
                $('#deleteModal').modal('hide');
                alert('删除产品成功！');
                
                // 在实际应用中，这里应该发送AJAX请求到后端删除数据
                // 然后重新加载表格数据
            }
        }

        // 搜索产品
        function searchProducts() {
            var productName = $('#searchName').val().toLowerCase();
            var categoryId = $('#searchCategory').val();
            var status = $('#searchStatus').val();
            
            // 简单的客户端搜索
            $('#simpleProductTable tbody tr').each(function() {
                var row = $(this);
                var nameMatch = productName === '' || row.find('td:eq(2)').text().toLowerCase().indexOf(productName) > -1;
                var categoryMatch = categoryId === '' || getCategoryId(row.find('td:eq(4)').text()) == categoryId;
                var statusMatch = status === '' || getStatusId(row.find('td:eq(9)').text()) == status;
                
                if (nameMatch && categoryMatch && statusMatch) {
                    row.show();
                } else {
                    row.hide();
                }
            });
        }

        // 重置搜索
        function resetSearch() {
            $('#searchForm')[0].reset();
            $('#simpleProductTable tbody tr').show();
        }

        // 模态框关闭时重置状态
        $('#productModal').on('hidden.bs.modal', function () {
            $('#productForm')[0].reset();
            $('#productForm input, #productForm select, #productForm textarea').prop('disabled', false);
            $('.modal-footer .btn-primary').show();
            $('.modal-footer .btn-secondary').text('取消');
            $('#imagePreview').hide();
        });
        
        // 辅助函数 - 获取分类ID
        function getCategoryId(categoryName) {
            switch (categoryName) {
                case '谷物类': return 1;
                case '蔬菜类': return 2;
                case '水果类': return 3;
                case '肉类': return 4;
                case '水产类': return 5;
                default: return 0;
            }
        }
        
        // 辅助函数 - 获取状态ID
        function getStatusId(statusText) {
            if (statusText.indexOf('正常') > -1) return '0';
            if (statusText.indexOf('停用') > -1) return '1';
            return '';
        }
        
        // 模拟产品数据
        function getMockProductData(id) {
            var mockProducts = {
                1: {
                    productId: 1,
                    productName: '有机大米',
                    productCode: 'P001',
                    categoryId: 1,
                    status: '0',
                    unit: 'kg',
                    spec: '5kg/袋',
                    weight: 5,
                    price: 25.00,
                    shelfLife: 365,
                    storageCondition: '阴凉干燥处',
                    picUrl: '',
                    remark: '东北优质有机大米'
                },
                2: {
                    productId: 2,
                    productName: '新鲜胡萝卜',
                    productCode: 'P002',
                    categoryId: 2,
                    status: '0',
                    unit: 'kg',
                    spec: '散装',
                    weight: 1,
                    price: 3.50,
                    shelfLife: 7,
                    storageCondition: '冷藏',
                    picUrl: '',
                    remark: '新鲜采摘胡萝卜'
                },
                3: {
                    productId: 3,
                    productName: '红富士苹果',
                    productCode: 'P003',
                    categoryId: 3,
                    status: '0',
                    unit: 'kg',
                    spec: '精品装',
                    weight: 1,
                    price: 12.80,
                    shelfLife: 15,
                    storageCondition: '冷藏',
                    picUrl: '',
                    remark: '山东烟台红富士苹果'
                }
            };
            
            return mockProducts[id];
        }
    </script>
</body>
</html> 